define(function(require,exports,module){
	'use strict';
	
	var React = require('react');
	var $ = require('jquery');
	var bootstrap = require('bootstrap');
	var XDate = require('xdate');
	var xdate = new XDate();
	var moment = require('moment');
	var publicObj = require('lib/public');
	var token = publicObj.get_token();
	var fancybox = require('fancybox');

	/*DATE下拉框*/
	var SelectOptionDate = require('components/partial/SelectOptionDate');

	/*分页*/
	var Pager = require('components/partial/Pager');
	var DataList = require('./UserTableList/DataList');
	var DataSearchForm = require('./UserTableList/DataSearchForm');
	var DataForm = require('./UserTableList/DataForm');
    var UserDetailRecord = require('./UserTableList/UserDetailRecord');

	module.exports = React.createClass({
		loadDataSum:function(){
			var sql = "select count(*) as sum from qeeniao.user";
			var data = new Object();
			data.sql = sql;
			data.access_token = token;

			$.ajax({
				url:this.props.url,
				data:data,
				type:'post',
				dataType:'json',
				success:function(o){
                    if(this.isMounted()){
                        this.setState({'data_sum':o[0].sum});
                    }
				}.bind(this),
				error:function(xhr,status,err){
					console.error('获取数据失败!',status,err.toString());
				}.bind(this)
			})
		},
		getInitialState:function(){
			return {
				data:[],
                detail_data:[],
				data_list:[],
				data_sum:0,
				date_data:[],
				date:'',
				page:0,
				next_stop:false,
				pre_stop:true,
                detail_page:0,
                detail_next_stop:false,
                detail_pre_stop:true,
				keys:'',
                user_id:''
			};
		},
		listData:function(p,keys){

			if(!p){
				p = 1;
			}

			p = parseInt(p);
			var page = p - 1;
			page = page > 0 ? page : 0;
			var pagesize = 10;
			var limit = " limit "+(page * pagesize)+","+pagesize+" ";

			var data = new Object();
			if(keys){
				data.sql = "SELECT \
							headimg,\
							user_id,\
							ctime as date,\
							email,\
							gender,\
							mobilephone as mobile,\
							nick,\
							username,\
							referrer \
							FROM qeeniao.user \
							WHERE (username like '%"+keys+"%' or email like '%"+keys+"%' or nick like '%"+keys+"%') order by ctime DESC "+limit;
			}else{
				
				if(this.state.keys){
					data.sql = "SELECT \
								headimg,\
								user_id,\
								ctime as date,\
								email,\
								gender,\
								mobilephone as mobile,\
								nick,\
								username,\
								referrer \
								FROM qeeniao.user \
								WHERE (username like '%"+this.state.keys+"%' or email like '%"+this.state.keys+"%' or nick like '%"+this.state.keys+"%') order by ctime DESC "+limit;
				}else{
					data.sql = "SELECT \
								headimg,\
								user_id,\
								ctime as date,\
								email,\
								gender,\
								mobilephone as mobile,\
								nick,\
								username,\
								referrer \
								FROM qeeniao.user order by ctime DESC "+limit;
				}
			}
			
			data.access_token = token;

			$.ajax({
				url:this.props.url,
				data:data,
				type:'post',
				dataType:'json',
				success:function(o){
					this.setState({'data_list':o});

					if(o.length < pagesize){
						this.setState({'next_stop':true});
					}else{
						this.setState({'next_stop':false});
					}

					if((p-1) <= 0){
						this.setState({'pre_stop':true});
					}else{
						this.setState({'pre_stop':false});
					}

					this.setState({page:p});

				}.bind(this),
				error:function(xhr,status,err){
					console.error('获取数据失败!',status,err.toString());
				}.bind(this)
			})
		},
		componentDidMount:function(){
            this.listData(1);
            this.loadDataSum();

            $('.fancybox').fancybox({
                image    : '<img class="fancybox-image" src="{href}" alt="" />'
            });
		},
		showData:function(){
			$('#myModal').modal();
		},
		searchData:function(keys){
			this.setState({'keys':keys});
			this.listData(1,keys);
		},
        loadDetailData:function(p,user_id){
            if(!p){
                p = 1;
            }

            p = parseInt(p);
            var page = p - 1;
            page = page > 0 ? page : 0;
            var pagesize = 10;
            var limit = " limit "+(page * pagesize)+","+pagesize+" ";

            var sql;
            if(user_id){
                sql = "SELECT r.record_id,\
                        r.user_id,\
                          r.rt_id,\
                          r.money,\
         r.content as description,\
                          r.ctime,\
                          r.rtime,\
                        rt.content\
                        from qeeniao.record r left join qeeniao.record_type rt on rt.type_id = r.rt_id and rt.user_id = r.user_id\
                        where r.user_id= "+user_id+"\
                        order by r.record_id DESC "+limit;
            }else{
                if(this.state.user_id){
                    sql = "SELECT r.record_id,\
                        r.user_id,\
                          r.rt_id,\
                          r.money,\
         r.content as description,\
                          r.ctime,\
                          r.rtime,\
                        rt.content\
                        from qeeniao.record r left join qeeniao.record_type rt on rt.type_id = r.rt_id and rt.user_id = r.user_id\
                        where r.user_id= "+this.state.user_id+"\
                        order by r.record_id DESC "+limit;
                }else{
                    return ;
                }
            }

            $.ajax({
                url:this.props.url,
                data:{'access_token':token,'sql':sql},
                dataType:'json',
                type:'post',
                success:function(o){
                    if(this.isMounted()){
                        this.setState({detail_data:o});

                        if(o.length < pagesize){
                            this.setState({'detail_next_stop':true});
                        }else{
                            this.setState({'detail_next_stop':false});
                        }

                        if((p-1) <= 0){
                            this.setState({'detail_pre_stop':true});
                        }else{
                            this.setState({'detail_pre_stop':false});
                        }

                        this.setState({detail_page:p});
                    }
                }.bind(this),
                error:function(xhr,status,error){
                    console.error(xhr,error.toString());
                }.bind(this)
            })
        },
        showDetail:function(e){
            var user_id = e.target.dataset.userid;
            if(user_id){
                $('#UserDetailRecord').modal();
                this.setState({'user_id':user_id});
                this.loadDetailData(1,user_id);
            }
        },
		render:function(){
			var data_list;
			if(this.state.data_list.length > 0){
				data_list = this.state.data_list.map(function(j){
                    var headimg;
                    var date;

                    if(j.headimg){
                        headimg = "http://7u2r0u.com1.z0.glb.clouddn.com/" + j.headimg;
                    }else{
                        headimg = "images/default.png";
                    }

                    var imgLoadError = function(e){
	                    console.log(e.target.src);
	                    e.target.src = 'images/default.png';
	                }

                    date = moment(parseInt(j.date) * 1000).format('YYYY-MM-DD HH:mm:ss');

                    var username = j.nick ? j.nick : j.username;

					return (
						<tr>
							<td>
								<a href={headimg} className="fancybox" data-fancybox-type="image">
									<img onError={imgLoadError} className="img-circle" src={headimg} style={{'width':'32px','height':'32px'}}/>
								</a>
							</td>
							<td>{username}</td>
							<td>{j.email}</td>
							<td>{date}</td>
							<td>
								<form className="form">
									<button onClick={this.showDetail} data-userid={j.user_id} className="btn btn-default btn-sm">记录详情</button>
								</form>
							</td>
						</tr>
					);
				}.bind(this));
			}

			var pager_props = {
				page : this.state.page,
				pre_stop:this.state.pre_stop,
				next_stop:this.state.next_stop,
				listData : this.listData
			};

            var detail_pager_props = {
                page : this.state.detail_page,
                pre_stop:this.state.detail_pre_stop,
                next_stop:this.state.detail_next_stop,
                listData : this.loadDetailData
            };

			return (
				<div className="panel panel-default" style={{marginTop:10+'px'}}>
					<div className="panel-heading">
						<div className="panel-title">
							<h4 className="">
								{this.props.title} :
								<span className="red">{this.state.data_sum}个</span>

							</h4>
						</div>

                        <UserDetailRecord id="UserDetailRecord" url={this.props.url} select_user_id={this.state.user_id} data={this.state.detail_data} pager_props={detail_pager_props}/>

					</div>
					<div className="panel-body">
						<DataSearchForm searchHandle={this.searchData} createHandle={this.showData}/>
						<DataForm id="myModal" />
					</div>
				
					<div className="panel-body">
						<DataList TrDataList={data_list}/>
					</div>

					<div className="panel-body">
						<Pager {...pager_props}/>
					</div>
				</div>
			);
		}
	});
});